package com.ck.common.utils.security.sign;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CtAes {
    public static final String bm = "UTF-8";

    private String vipara;
    private String aseKey;

    public CtAes(String vipAra, String aesKey) {
        this.vipara = vipAra;
        this.aseKey = aesKey;
    }

    public String encrypt(String cleartext) {
        //加密方式： AES128(CBC/PKCS5Padding) + Base64, 私钥：aabbccddeeffgghh
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(vipara.getBytes());
            //两个参数，第一个为私钥字节数组， 第二个为加密方式 AES或者DES
            SecretKeySpec key = new SecretKeySpec(aseKey.getBytes(), "AES");
            //实例化加密类，参数为加密方式，要写全
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //PKCS5Padding比PKCS7Padding效率高，PKCS7Padding可支持IOS加解密
            //初始化，此方法可以采用三种方式，按加密算法要求来添加。
            // （1）无第三个参数
            // （2）第三个参数为SecureRandom random = new SecureRandom();中random对象，随机数。(AES不可采用这种方法)
            // （3）采用此代码中的IVParameterSpec
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            //加密操作,返回加密后的字节数组，然后需要编码。主要编解码方式有Base64, HEX, UUE,7bit等等。此处看服务器需要什么编码方式
            byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm));

            //return new BASE64Encoder().encode(encryptedData);
            return new Base64().encodeAsString(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String decrypt(String encrypted) {
        try {
            byte[] byteMi = new Base64().decode(encrypted);
            IvParameterSpec zeroIv = new IvParameterSpec(vipara.getBytes());
            SecretKeySpec key = new SecretKeySpec(
                    aseKey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            //与加密时不同MODE:Cipher.DECRYPT_MODE
            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
            byte[] decryptedData = cipher.doFinal(byteMi);
            return new String(decryptedData, bm);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void main(String[] args) {
        CtAes ctAes = new CtAes("19EC4AEA4B60E330", "E7D11C69D17ECC79");

//        String encryptResult = "BgFWh/kZdqJBW6uTO/KtDBTabhgKjDJYjZg4IoLCtRhPsvPOJbTNVXM9r4oVl+1HQqCeRc/a0FKs71JP3ZYJoV0tenUQolob/VuSPAbfenhCAlPSzHLKLFIpcC8P5M6672fSF6GB8sXm/5Dt8UjPYM0EPARenaBL13mA3RILmw5nDftRKIa/DBm8ExVU5RAY5n2qKoinuN547BeJgYoHwtv3m0gPmYOUy1+hvb5S+Sxz/zFI8+8w2WFYUZFR3vK5xiWUUx6FDrBG3HSPWxUwoVoSTFqpCfxogHZ7ccaltee2rtwLo+wcSOMwCdNwgpj9MbLiuvBtYnbKronW7u60C2ak16WUUWgqHqM2DMX9eOfLhRTISAWeJDX0AUIHG7brd3l45DklbfxGR0w9F44JOZTbv/BbF2FGsif4kPu4t8ti2LALoPkC7M82/vaPeUD2unJptZd44hPElaEfOdtU4FDUhTm7lSwvFPgwTxdrlqbMvu+meuEUaPZsdAtl/xxLWayqAmfROjRchLIvFmcOIJrh7P7l3S5YZgKF8cpNCpmPPhOfQt+xMskHvtJ1aLJp";
//        String decryptResult = ctAes.decrypt(encryptResult);
//        System.out.println("解密后：" + decryptResult);

        //业务接口请求报文加密
        String encryptResult2 = "{\"id\":\"1\"}";
//        String decryptResult2 = ctAes.encrypt(encryptResult2);
        String decryptResult2 = "wBiXBfLy4aoWilXFtr0qhcU5WuvurV5olvaLsxxM+Y3ILcmayjg+TGzQyDE9VpCM5l4qo9JBwf9qXj6KCKtozkG2/T++Xl/jMc4tmaCdd459jcuX62QgxH2F29sZsId75OW1yt1QHeeyQ9X6XP+/fCk+e/CVZ31Om96HNSoIpIxxS+5SC9ISgHySpl395lJ8mjMq0pLZod+lq777c3ux7YxMMe9IhpRBPsTIuHN0JOamFIr/NFtx6O3yay19rB+l";
//        System.out.println("加密后: "+decryptResult2);

        String decrypt = ctAes.decrypt(decryptResult2);
        System.out.println("解密后: "+decrypt);
    }
}
